<template>
    <Row type="flex" justify="space-around" class="code-row-bg">
        <Spin fix v-if="formLoading">
            <Icon type="ios-loading" size=18 class="demo-spin-icon-load"></Icon>
            <div>Loading</div>
        </Spin>
        <Form ref="selfCheckForm" :model="dataClone" :rules="ruleCustom" class="self-check-form w" label-position='top'
              :show-message="false">
            <Row type="flex" justify="space-around" class="code-row-bg">
                <Col span="11">
                    <FormItem label="二级集团：">
                        <Input v-model="dataClone.belongOrgName" type="text" readonly></Input>
                    </FormItem>
                </Col>
                <Col span="11">
                    <FormItem label="年度：">
                        <Input placeholder="请输入" class="w" v-model="dataClone.year" readonly></Input>
                    </FormItem>
                </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
                <Col span="11">
                    <FormItem label="企业名称：" prop="companyId">
                        <Input v-model="dataClone.companyName" type="text" readonly></Input>
                    </FormItem>
                </Col>
                <Col span="11">
                    <FormItem label="行业分类：">
                        <Input v-model="dataClone.industryName" type="text" readonly></Input>
                    </FormItem>
                </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
                <Col span="11">
                    <FormItem label="">
                        自评时间：{{this.renderViewDate(dataClone.selfLevelTime)}}
                    </FormItem>
                </Col>
                <Col span="11">
                    <FormItem label="">
                        企业负责人：{{dataClone.managerName}}
                    </FormItem>
                </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
                <Col span="23">
                    <b>自查存在的问题：</b>
                    <Table :columns="problemColumns" :row-class-name="rowClassName" :data="dataClone.selfCheckItems"
                           style="margin-bottom: 15px" :content="self"></Table>
                </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
                <Col span="11">
                    <FormItem label="">
                        是否存在否决项： {{dataClone.hasVeto1==1?'是':dataClone.hasVeto1==0?'否':''}}
                    </FormItem>
                </Col>
                <Col span="11">
                    <FormItem label="">
                        标准分： {{dataClone.standardScore}}
                    </FormItem>
                </Col>
                <Col span="23">
                    <FormItem label="" v-if="dataClone.hasVeto1==1">
                        否决项内容：{{dataClone.vetoContent1}}
                    </FormItem>
                </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
                <Col span="11">
                    <FormItem label="">
                        评定得分：{{dataClone.evaluationScore1}}
                    </FormItem>
                </Col>
                <Col span="11">
                    <FormItem label="">
                        涉及得分：{{dataClone.involvedScore1}}
                    </FormItem>
                </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
                <Col span="11">
                    <FormItem label="">
                        综合评定得分：{{dataClone.integretedScore1}}
                    </FormItem>
                </Col>
                <Col span="11">
                    <FormItem label="" prop="level">
                        评定等级：{{dataClone.level1==null?'':enStdCodingCodeIdMap[dataClone.level1].codingName}}
                    </FormItem>
                </Col>
            </Row>

            <Row type="flex" justify="space-around" class="code-row-bg">
                <Col span="23">
                    <b>现场审核中发现的其他不符合项：</b><!--(否决项和有评定扣分项的存在的问题必填)-->
                    <FormItem label="" prop="sceneCheckItems" v-show="dataClone.sceneCheckItems.length<1 && this.currentUser.loginId === this.Common.admin">
                        <div class="fixed aR" style='margin-top: -30px;'>
                            <Button class="" size='small' @click="addRowStandard('sceneCheckItems')">编辑</Button>
                        </div>
                    </FormItem>
                    <Table :columns="otherProblemColumns" style="margin-bottom: 10px" :data="dataClone.sceneCheckItems"
                           :content="self">
                        <template slot-scope="{ row, index }" slot="problem">
                            <Input type="textarea" :autosize="{minRows:2,maxRows:5}"
                                   v-model="dataClone.sceneCheckItems[index].problem"></Input>
                        </template>
                        <template slot-scope="{ row, index }" slot="problemCategory">
                            <Select v-model="dataClone.sceneCheckItems[index].problemCategory">
                                <Option v-for="item in environmentProtectionList" :value="item.codingCodeId"
                                        :key="item.codingCodeId">{{ item.codingName }}
                                </Option>
                            </Select>
                        </template>
                        <template slot-scope="{ row, index }" slot="checkTime">
                            <DatePicker type="date" v-model="dataClone.sceneCheckItems[index].checkTime"></DatePicker>
                        </template>
                        <template slot-scope="{ row, index }" slot="completeTime">
                            <DatePicker type="date"
                                        v-model="dataClone.sceneCheckItems[index].completeTime"></DatePicker>
                        </template>

                        <template slot-scope="{ row, index }" slot="ifInvolved">
                            <div v-if="!row.score && row.project !=='加分项'&&row.project !=='扣分项'"></div>
                            <i-switch :value="true" v-else v-model="dataClone.sceneCheckItems[index].ifInvolved">
                                <!--<span slot="open">{{ row.project ==='加分项'||row.project ==='扣分项'?0-row.deductScore:row.score }}</span>-->
                                <span slot="open">{{ row.project ==='加分项'||row.project ==='扣分项'?0:row.score }}</span>
                                <span slot="close">0</span>
                            </i-switch>
                        </template>
                        <template slot-scope="{ row, index }" slot="deductScore">
                            <div v-if="(!row.score&&row.project !=='加分项'&&row.project !=='扣分项') || !row.ifInvolved"></div>
                            <!--row.project === '否决项'-->
                            <InputNumber v-else-if="row.project ==='加分项'" :max='0'
                                         v-model="dataClone.sceneCheckItems[index].deductScore"></InputNumber>
                            <InputNumber v-else-if="row.project ==='扣分项'" :min="0"
                                         v-model="dataClone.sceneCheckItems[index].deductScore"></InputNumber>
                            <InputNumber v-else :min="0" :disabled="!row.ifInvolved" :max="row.score"
                                         v-model="dataClone.sceneCheckItems[index].deductScore"></InputNumber>
                        </template>
                        <template slot-scope="{ row, index }" slot="action">
                            <!--<Button shape="circle" size="small" icon="md-close" @click="removeRowStandard('sceneCheckItems', index)"></Button>-->
                            <!--<Button size="small" type="primary" @click="saveOne(row, index,'sceneCheckItems')">保存</Button>-->
                            <Button size="small" type="primary" style="font-size: 10px" :disabled="row.state!=='NOT_RECTIFIED' && row.state!=='START'"
                                    @click="viewPicture(row.id);itemModel =true;questionItem = {...row};questionItem.index = index">评价</Button>
                            <!--<Button size="small" type="error" style="margin-left: 4px;font-size: 10px" :disabled="!row.questionId || row.state!=='START'"-->
                                    <!--@click="reportQuestion(row,index,'sceneCheckItems')">上报</Button>-->
                            <!--:disabled="row.questionId==''|| row.questionId==null || row.questionId==undefined || row.state!=='START'"-->
                        </template>
                    </Table>
                </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
                <Col span="11">
                    <FormItem label="评定人：" prop="auditor">
                        <Input v-model="dataClone.auditor" type="text"></Input>
                    </FormItem>
                </Col>
                <Col span="11">
                    <FormItem label="现场评定时间：" prop="levelTime">
                        <DatePicker type="date" placeholder="选择日期" class='w' v-model="dataClone.levelTime"></DatePicker>
                        <!--@on-change="setSelfLevelTime" @on-clear="clearSelfLevelTime" :value="dataClone.levelTime" format="yyyy-MM-dd"-->
                    </FormItem>
                </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
                <Col span="11">
                    <FormItem label="是否存在否决项：" prop="hasVeto">
                        <Radio-group v-model.sync="dataClone.hasVeto" @on-change="cleanVetoContent">
                            <Radio label="1">是</Radio>
                            <Radio label="0">否</Radio>
                        </Radio-group>
                    </FormItem>
                </Col>
                <Col span="11">
                    <FormItem label="标准分：" prop="standardScore">
                        <InputNumber class="w" v-model='dataClone.standardScore' :min="0" readonly></InputNumber>
                    </FormItem>
                </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
                <Col span="23">
                    <FormItem label="否决项内容：" prop="vetoContent" v-if="dataClone.hasVeto==1">
                        <Input type="text" v-model="dataClone.vetoContent" placeholder="请输入否决项"></Input>
                    </FormItem>
                    <!--<FormItem label="综合评定意见：" prop="score"></FormItem>-->
                </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
                <Col span="11">
                    <FormItem label="评定得分：" prop="evaluationScore">
                        <InputNumber class="w" v-model='evaluationScore' :min="0" readonly></InputNumber>
                    </FormItem>
                </Col>
                <Col span="11">
                    <FormItem label="涉及得分：" prop="involvedScore">
                        <InputNumber class="w" v-model='dataClone.involvedScore' :min="0" readonly></InputNumber>
                    </FormItem>
                </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
                <Col span="11">
                    <FormItem label="综合评定得分：" prop="integretedScore">
                        <InputNumber class="w" v-model='dataClone.integretedScore' readonly :min="0"></InputNumber>
                    </FormItem>
                </Col>
                <Col span="11">
                    <FormItem label="评定等级：" prop="level">
                        <Select class='w' v-model="dataClone.level" :disabled="true">
                            <Option v-for="item in enStdMap" :value="item.codingCodeId" :key="item.codingCodeId">{{
                                item.codingName }}
                            </Option>
                        </Select>
                    </FormItem>
                </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
                <Col span="11">
                    <FormItem label='填报人：' prop='levelReport'>
                        <Input type='text' v-model='dataClone.levelReport' readonly></Input>
                    </FormItem>
                </Col>
                <Col span="11">
                    <FormItem label='手机号：' prop='levelTelphone'>
                        <Input type='text' v-model='dataClone.levelTelphone'></Input>
                    </FormItem>
                </Col>
            </Row>
        </Form>
        <Modal title="选择标准" :transfer=false v-model="selectDialogShow" v-if="selectDialogShow" :width=1000
               :styles="{height:'726px'}"
               class-name='limit-height-dialog'>
            <select-item-table
                    ref="selectItemTable"
                    :dialogResourceSelectedDataArr="[]"
                    :dialogResourceSearchParams="{curCompanyId:currentUser.companyId}"
                    :dialogResourceSearchFormItems="dialogResourceSearchFormItems"
                    :dialogResourceQueryUrl="dialogResourceQueryUrl"
                    :dialogResourceColumns="dialogResourceColumns"
                    dialogResourceTableDataKey="itemId"
            ></select-item-table>
            <div slot="footer">
                <Button class='ivu-btn-save' @click="selectItemTableSubmitBtnClickHandle">确定</Button>
                <Button class='ivu-btn-cancel' @click="selectDialogShow=false">关闭</Button>
            </div>
        </Modal>

        <Modal title="图片上传" :transfer=false footer-hide v-model="pictureModal" :width=600>
            <Form ref="dataForm" :label-width="100">
                <Row type="flex" justify="space-around" class="code-row-bg" style="margin-top: 10px">
                    <Col span="23">
                        <FormItem :label="!editPicture?'上传图片：':'图片：'">
                            <div class="demo-upload-list" v-for="item in uploadList" :key="item.id">
                                <img :src="item.url">
                                <div class="demo-upload-list-cover">
                                    <Icon type="ios-eye-outline" @click.native="handleView(item.name,item.url)"></Icon>
                                    <Icon type="ios-trash-outline" v-show="!editPicture"
                                          @click.native="handleRemove(item)"></Icon>
                                </div>
                            </div>
                            <Upload
                                    ref="upload"
                                    :show-upload-list="false"
                                    :format="['jpg','jpeg','png','gif']"
                                    accept="image/jpg, image/jpeg,image/png,image/gif,image/bmp"
                                    :max-size="1024"
                                    :before-upload="handleBeforeUpload"
                                    multiple
                                    type="drag"
                                    :disabled="editPicture"
									v-show='!editPicture'
                                    :action="upUrl"
                                    style="display: inline-block;width:58px;">
                                <div style="width: 58px;height:58px;line-height: 58px;">
                                    <Icon type="ios-camera" size="20"></Icon>
                                </div>
                            </Upload>
                            <Modal title="View Image" v-model="visible">
                                <img :src="viewUrl" v-if="visible" style="width: 100%">
                                <div slot="footer">
                                    <Button type="primary" class='ivu-btn-save' @click="visible=false">关闭</Button>
                                </div>
                            </Modal>
                        </FormItem>
                    </Col>
                </Row>
            </Form>
        </Modal>

        <Modal :mask-closable="false" :transfer=false v-model="itemModel" :width=800 :styles="{height:'700px'}"
               title="问题评价"
               @on-cancel="itemModel=false,questionItem={}">
            <Row>
                <Col span="24">
                    <Form ref="itemForm" :class="'modal-form'" :show-message="false" :model="questionItem"
                          :rules="itemRuleCustom" label-position="top">
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="23">
                                <FormItem label='评价内容：' prop='content'>
                                    <Input class='' type="textarea" :autosize="{minRows:2,maxRows:5}" disabled
                                           v-model='questionItem.content'></Input>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="23">
                                <FormItem label='评分标准：' prop='standard'>
                                    <Input class='' type="textarea" :autosize="{minRows:2,maxRows:5}" disabled
                                           v-model='questionItem.standard'></Input>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11">
                                <FormItem label='评价项目：' prop='project'>
                                    <Input class='' type='text' disabled v-model='questionItem.project'></Input>
                                </FormItem>
                            </Col>
                            <Col span="3">
                                <FormItem label='分值：' prop='score'>
                                    <Input class='' type='text' disabled v-model='questionItem.score'></Input>
                                </FormItem>
                            </Col>
                            <Col span="3">
                                <FormItem label='涉及得分：' prop='ifInvolved'>
                                    <i-switch :value="true" v-model="questionItem.ifInvolved">
                                        <span slot="open">{{ questionItem.project ==='加分项'||questionItem.project ==='扣分项'?0:questionItem.score }}</span>
                                        <span slot="close">0</span>
                                    </i-switch>
                                </FormItem>
                            </Col>
							<Col span="3">
							    <FormItem label='评定扣分：' prop='deductScore' v-if="questionItem.ifInvolved">
							        <div v-if="(!questionItem.score&&questionItem.project !=='加分项'&&questionItem.project !=='扣分项') || !questionItem.ifInvolved"></div>
							        <!--row.project === '否决项'-->
							        <InputNumber style="width: 100%" v-else-if="questionItem.project ==='加分项'"
							                     :max='0' v-model="questionItem.deductScore"></InputNumber>
							        <InputNumber style="width: 100%" v-else-if="questionItem.project ==='扣分项'"
							                     :min="0" v-model="questionItem.deductScore"></InputNumber>
							        <InputNumber style="width: 100%" v-else :min="0"
							                     :disabled="!questionItem.ifInvolved" :max="questionItem.score"
							                     v-model="questionItem.deductScore"></InputNumber>
							    </FormItem>
							</Col>
                        </Row>
                        <div v-if="questionItem.ifInvolved &&(questionItem.deductScore !=0 || questionItem.project === '否决项')">
                            <Row type="flex" justify="space-around" class="code-row-bg">
                                <Col span="11">
                                    <FormItem label='问题类别：' prop='problemCategory'>
                                        <Select v-model="questionItem.problemCategory" label-in-value
                                                @on-change='(val)=>{questionItem.problemCategory=val.value;questionItem.problemCategoryName=val.label;}'>
                                            <Option v-for="item in environmentProtectionList" :value="item.codingCodeId"
                                                    :key="item.codingCodeId">{{ item.codingName }}
                                            </Option>
                                        </Select>
                                    </FormItem>
                                </Col>
                                <Col span="11">
                                    <!-- <FormItem label='评定扣分：' prop='deductScore'>
                                        <div v-if="(!questionItem.score&&questionItem.project !=='加分项'&&questionItem.project !=='扣分项') || !questionItem.ifInvolved"></div>
                                        <InputNumber style="width: 100%" v-else-if="questionItem.project ==='加分项'"
                                                     :max='0' v-model="questionItem.deductScore"></InputNumber>
                                        <InputNumber style="width: 100%" v-else-if="questionItem.project ==='扣分项'"
                                                     :min="0" v-model="questionItem.deductScore"></InputNumber>
                                        <InputNumber style="width: 100%" v-else :min="0"
                                                     :disabled="!questionItem.ifInvolved" :max="questionItem.score"
                                                     v-model="questionItem.deductScore"></InputNumber>
                                    </FormItem> -->
                                </Col>
                            </Row>
                            <Row type="flex" justify="space-around" class="code-row-bg">
                                <Col span="23">
                                    <FormItem label='存在的问题：' prop='problem'>
                                        <Input class='' placeholder="请填写存在的问题" type="textarea"
                                               :autosize="{minRows:2,maxRows:5}" v-model='questionItem.problem'></Input>
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row type="flex" justify="space-around" class="code-row-bg" style="margin-top: 10px">
                                <Col span="23">
                                    <FormItem label="上传图片：">
                                        <div class="demo-upload-list" v-for="item in uploadList" :key="item.id">
                                            <img :src="item.url">
                                            <div class="demo-upload-list-cover">
                                                <Icon type="ios-eye-outline"
                                                      @click.native="handleView(item.name,item.url)"></Icon>
                                                <Icon type="ios-trash-outline"
                                                      @click.native="handleRemove(item)"></Icon>
                                            </div>
                                        </div>
                                        <Upload
                                                :show-upload-list="false"
                                                :format="['jpg','jpeg','png','gif']"
                                                accept="image/jpg, image/jpeg,image/png,image/gif,image/bmp"
                                                :max-size="1024"
                                                :before-upload="handleBeforeUpload"
                                                multiple
                                                type="drag"
                                                :action="upUrl"
                                                style="display: inline-block;width:58px;">
                                            <div style="width: 58px;height:58px;line-height: 58px;">
                                                <Icon type="ios-camera" size="20"></Icon>
                                            </div>
                                        </Upload>
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row type="flex" justify="space-around" class="code-row-bg">
                                <Col span="11">
                                    <FormItem label='检查时间：' prop='checkTime'>
                                        <DatePicker class="w" placeholder="请选择检查时间" v-model='questionItem.checkTime' :clearable="false"
                                                    :options="{disabledDate(date) {return date && date.valueOf() > new Date();}}"></DatePicker>
                                    </FormItem>
                                </Col>
                                <Col span="11">
                                    <FormItem label='完成时限：' prop='completeTime'>
                                        <DatePicker class="w" placeholder="请选择完成时限" v-model='questionItem.completeTime' :clearable="false"
                                                    :options="{disabledDate(date) {return date &&
                                                    questionItem.checkTime && date.valueOf() < questionItem.checkTime;}}"></DatePicker>
                                    </FormItem>
                                </Col>
                                <Col span="23">
                                    <Alert type="warning">{{this.Common.questionWarn}}</Alert>
                                </Col>
                            </Row>
                        </div>
                    </Form>
                </Col>
            </Row>
            <div slot="footer">
                <Button type="primary" class='ivu-btn-save' @click="saveOne(questionItem, questionItem.index,'sceneCheckItems')">确定</Button>
                <Button type="primary" class='ivu-btn-cancel' @click="itemModel=false,questionItem={}">取消</Button>
                <!--<Button v-if="mode === 'view'" class='ivu-btn-save' @click="dialogShow=false">关闭</Button>-->
            </div>
        </Modal>
    </Row>
</template>

<script>
    import {Api} from "@/api";
    import {sessionStorage} from '@/common/cacheUtils.js';

    var cascaderDom = () => import('@/components/cascader-dom.vue');
    import _deepclone from 'lodash/cloneDeep'
    import SelectItemTable from "@/components/SelectItemTable.vue"
    import pageCommonFunction from '@/components/pageCommonFunction.js'

    function countLevel(newVal) {
        let map = this.enStdMap
        let level = 1
        let score = this.dataClone.integretedScore
        if (370 > score || this.dataClone.hasVeto == 1) {
            level = 4
        } else if (score >= 470) {
            level = 1
        } else if (470 > score && score >= 420) {
            level = 2
        } else if (420 > score && score >= 370) {
            level = 3
        }
        this.$set(this.dataClone, 'level', map[level].codingCodeId)
    }

    export default {
        name: "self-check-form",
        props: ['data', 'enStdMap', 'mode', 'enStdCodingCodeIdMap'],
        data() {
            return {
                formLoading: false,
                dataClone: {},
                self: this,
                problemColumns: [
                    {title: '序号', type: 'index', align: 'center', width: 60},
                    {title: '评价项目', key: 'project', align: 'center', minWidth: 90},
                    {title: '评价内容', key: 'content', align: 'center', minWidth: 110, tooltip: true},
                    {title: '评分标准', key: 'standard', align: 'center', minWidth: 110, tooltip: true},
                    {title: '分值', key: 'score', width: 60, align: 'center'},
                    {
                        title: '涉及得分', key: 'ifInvolved', width: 60, align: 'center',
                        render: (h, params) => {
                            return h('span', [
                                (!params.row.score && params.row.project !== '加分项' && params.row.project !== '扣分项') || !params.row.ifInvolved ? '' :
                                    params.row.project === '加分项' || params.row.project === '扣分项' ? params.row.ratingScore : params.row.score])
                        }
                    },
                    {title: '存在的问题', key: 'problem', minWidth: 100, align: 'center',},
                    {title: '问题类别', key: 'problemCategoryName', width: 90, align: 'center',},
                    {title: '检查时间', key: 'checkTime', width: 100, align: 'center', render: this.renderCellDate},
                    {title: '完成时限', key: 'completeTime', width: 100, align: 'center', render: this.renderCellDate},
                    {
                        title: '自评得分', key: 'ratingScore', width: 60, align: 'center',
                        render: (h, params) => {
                            return h('span', [(!params.row.score && params.row.project !== '加分项' && params.row.project !== '扣分项') || !params.row.ifInvolved ? '' : params.row.ratingScore])
                        }
                    },
                    {title: '整改情况', key: 'rectificationDetail', minWidth: 110, align: 'center',tooltip: true},
                    {
                        width: 60,
                        title: '照片',
                        key: 'img',
                        align: 'center',
                        slot: 'img',
                        render: (h, {row, index}) => {
                            return h("icon", {
                                props: {
                                    type: 'md-eye',
                                    size: '20'
                                },
                                style: {
                                    cursor: 'pointer'
                                },
                                on: {
                                    click: () => {
                                        this.pictureModal = true
                                        this.editPicture = true
                                        this.viewPicture(row.id);
                                    }
                                }
                            });
                        }
                    },
                    {
                        title: '评定扣分', key: 'deductScore', width: 60, align: 'center',
                        render: (h, params) => {
                            return h('span', [
                                ((!params.row.score || !params.row.ifInvolved) ? '' : params.row.deductScore)
                            ]);
                        }
                    },
                ],
                otherProblemColumns: [
                    {title: '序号', key: 'seqNo', align: 'center', width: 60},
                    {title: '评价项目', key: 'project', align: 'center', width: 90},
                    {title: '评价内容', key: 'content', align: 'center', width: 120, tooltip: true},
                    {title: '评分标准', key: 'standard', align: 'center', width: 120, tooltip: true},
                    {title: '分值', key: 'score', width: 65, align: 'center'},
                    // {title: '涉及得分', key: 'ifInvolved',slot: 'ifInvolved', width: 65, align: 'center'},
                    {
                        title: '涉及得分', key: 'ifInvolved', width: 60, align: 'center',
                        render: (h, params) => {
                            return h('span', [
                                (!params.row.score && params.row.project !== '加分项' && params.row.project !== '扣分项') || !params.row.ifInvolved ? '' :
                                    params.row.project === '加分项' || params.row.project === '扣分项' ? 0 - params.row.deductScore : params.row.score])
                        }
                    },
                    {title: '存在的问题', key: 'problem', minWidth: 120, align: 'center'},
                    {
                        width: 60,
                        title: '照片',
                        key: 'img',
                        align: 'center',
                        slot: 'img',
                        render: (h, {row, index}) => {
                            return h("icon", {
                                props: {
                                    type: 'md-eye',
                                    size: '20'
                                },
                                style: {
                                    cursor: 'pointer'
                                },
                                on: {
                                    click: () => {
                                        this.editPicture = false
                                        this.pictureModal = true
                                        this.viewPicture(row.id);
                                    }
                                }
                            });
                        }
                    },
                    {title: '问题类别', key: 'problemCategoryName', width: 90, align: 'center',},
                    {title: '检查时间', key: 'checkTime', width: 100, align: 'center', render: this.renderCellDate},
                    {title: '完成时限', key: 'completeTime', width: 100, align: 'center', render: this.renderCellDate},
                    {
                        title: '评定扣分', key: 'deductScore', width: 60, align: 'center',
                        render: (h, params) => {
                            return h('span', [(!params.row.score || !params.row.ifInvolved) && params.row.project !== '加分项' && params.row.project !== '扣分项' ? '' :
                                params.row.deductScore])
                        }
                    },
                    {title: '评定人', key: 'createUserName', width: 75, align: 'center'},
                    {title: '操作', key: 'action', align: 'center', width: 140, slot: 'action'}
                ],
                ruleCustom: {
                    companyId: [{required: true, message: '请选择企业名称', trigger: 'blur'}],
                    levelTime: [{required: true, message: '请选择现场审核时间', trigger: 'blur', type: 'date'}],
                    auditor: [{required: true, message: '请选择审核人', trigger: 'blur'}],
                    manager: [{required: true, message: '请选择企业主管', trigger: 'blur'}],
                    levelTelphone: [{
                        validator: (rule, value, callback) => {
                            if (!(/^1[3456789]\d{9}$/.test(this.dataClone.levelTelphone))) {
                                callback(' ');
                            } else {
                                callback()
                            }
                        },
                        required: true,
                        trigger: 'blur'
                    }],
                    // sceneCheckItems: [{
                    //     validator: (rule, value, callback) => {
                    //         for (let i = 0, il = dataClone.sceneCheckItems.length; i < il; i++) {
                    //             let obj = dataClone.sceneCheckItems[i]
                    //             if (!obj.score ) {
                    //                 if (obj.problem === '' || obj.itemId === '') {
                    //                     callback(new Error('请填写自查问题表单中的每一项'));
                    //                     return
                    //                 }
                    //             }else {
                    //                 if (obj.ifInvolved && obj.deductScore>0&&(obj.problem === '' ||  obj.itemId === '')) {
                    //                     callback(new Error('请填写其他问题表单中的每一项'));
                    //                     return
                    //                 }
                    //            }
                    //         }
                    //         callback();
                    //     }, trigger: 'blue'
                    // }],
                    hasVeto: [{required: true, message: '请选择是否存在否决项', trigger: 'change'}],
                    vetoContent: [{required: true, message: '请输入否决项', trigger: 'change'}],
                    evaluationScore: [{pattern: /(\d+(\.\d+)?)/, message: '评定得分必须为数字', trigger: 'change'}],
                    involvedScore: [{pattern: /(\d+(\.\d+)?)/, message: '涉及得分必须为数字', trigger: 'change'}],
                    integretedScore: [{pattern: /(\d+(\.\d+)?)/, message: '综合评定得分必须为数字', trigger: 'change'}],
                    level: [{required: true, message: '请输入评定等级', trigger: 'blur'}]
                },
                itemModel: false,
                questionItem: {},
                itemRuleCustom: {
                    problemCategory: [{required: true, message: '请选择问题类别', trigger: 'change'}],
                    problem: [{required: true, message: '请填写存在的问题', trigger: 'change'}],
                    checkTime: [{required: true, message: '请选择检查时间', trigger: 'change', type: 'date'}],
                    completeTime: [{required: true, message: '请选择完成时限', trigger: 'change', type: 'date'}],
                },
                sending: false,
                // 選擇標準彈出框//
                dialogResourceType: '', // 类型
                selectDialogShow: false,
                dialogResourceSearchFormItems: [
                    {type: 'input', prop: 'project', label: '评价项目'},
                    {type: 'input', prop: 'content', label: '评价内容'},
                    {type: 'input', prop: 'standard', label: '评分标准'},
                    {type: 'input', prop: 'industryName', label: '行业分类'}
                ],
                dialogResourceQueryUrl: Api.queryEnStdStandard,
                dialogResourceColumns: [
                    {
                        align: 'center', type: 'selection', width: 60, filterMultiple: (row) => {
                            console.log(1 + row);
                            return true
                        }
                    },
                    {
                        title: '行业分类', width: 130, align: 'center', key: 'industryId',
                        render: (h, params) => {
                            return this.renderCellCode(h, params.row.industryId, 'env-00006');
                        }
                    },
                    {title: '评价项目', width: 130, align: 'center', key: 'project',},
                    {title: '评价内容', align: 'left', key: 'content',},
                    {title: '分值', width: 80, align: 'center', key: 'score',},
                    {title: '评分标准', align: 'left', key: 'standard',},
                ],

                industryNames: [],

                uploadList: [],
                upUrl: Api.uploadPTWFiles,
                viewUrl: Api.interestedPartiesUserFile,
                visible: false,
                imgName: '',
                pictureModal: false,
                editPicture: true,
                id: null,
                environmentProtectionList: [],
            }
        },
        watch: {
            'dataClone.hasVeto': countLevel,
            'dataClone.integretedScore': countLevel,
            'questionItem.ifInvolved':function (val) {
                if (val === false) {
                    this.questionItem.problemCategory= ''
                    this.questionItem.problem= ''
                    this.questionItem.problemCategoryName= ''
                    this.questionItem.checkTime= null
                    this.questionItem.completeTime= null
                    this.questionItem.deductScore= 0
                }
            },
			'questionItem.deductScore':function (val) {
			    if (this.questionItem.ifInvolved === true && this.questionItem.deductScore ==0 && this.questionItem.project !== '否决项') {
			        this.questionItem.problemCategory= ''
			        this.questionItem.problem= ''
			        this.questionItem.problemCategoryName= ''
			        this.questionItem.checkTime= null
			        this.questionItem.completeTime= null
			        this.questionItem.deductScore= 0
			    }
			}
        },
        created() {
            if (this.mode === 'add') {
                this.dataClone = {
                    levelTime: '',
                    hasVeto: '0',
                    selfCheckItems: [],
                    sceneCheckItems: [],
                    evaluationScore: 0,
                    involvedScore: 0,
                    integretedScore: 0,
                    standardScore: 0,
                    companyId: JSON.parse(sessionStorage('userId').get('userId')).companyId,
                    companyName: JSON.parse(sessionStorage('userId').get('userId')).companyName,
                    levelTelphone: JSON.parse(sessionStorage('userId').get('userId')).mobileNumber,
                    levelReport: JSON.parse(sessionStorage('userId').get('userId')).userName,
                    // auditorName:JSON.parse(sessionStorage('userId').get('userId')).userName,
                    auditor: JSON.parse(sessionStorage('userId').get('userId')).userName,
                    levelType: 2  //1 自评， 2现场评价
                }
                console.log(this.dataClone);
            } else {
                let dataClone = _deepclone(this.data)
                // if (!(dataClone.selfCheckItems instanceof Array)) {
                dataClone.selfCheckItems = []
                // }
                // if (!(dataClone.sceneCheckItems instanceof Array)) {
                dataClone.sceneCheckItems = []
                // }
                dataClone.levelTime = dataClone.levelTime ? dataClone.levelTime : new Date()
                dataClone.evaluationScore = (dataClone.evaluationScore !== null) ? dataClone.evaluationScore : 0
                dataClone.involvedScore = (dataClone.involvedScore !== null) ? dataClone.involvedScore : 0
                dataClone.integretedScore = (dataClone.integretedScore !== null) ? dataClone.integretedScore : 0
                dataClone.hasVeto = (dataClone.hasVeto !== null) ? dataClone.hasVeto : '0'
                dataClone.levelReport = (dataClone.levelReport !== null) ? dataClone.levelReport : JSON.parse(sessionStorage('userId').get('userId')).userName
                dataClone.levelTelphone = (dataClone.levelTelphone !== null) ? dataClone.levelTelphone : JSON.parse(sessionStorage('userId').get('userId')).mobileNumber
                dataClone.industryName = dataClone.industryId.split(',')
                // dataClone.auditor = JSON.parse(sessionStorage('userId').get('userId')).userName,
                dataClone.auditor = dataClone.auditor !== null ? dataClone.auditor : dataClone.expertNames
                this.dataClone = dataClone
            }
            window.dataClone = this.dataClone
        },
        mounted() {
            this.dataClone.enStdMap = this.enStdMap
            if (this.mode == 'edit') {
                this.$Spin.show()
                this.$http.get(Api.getEnvSelfCheck + this.data.id, {params: {type: 1}}).then((res) => {
                    if (res.data.status === 201) {
                        this.$Message.error(res.data.msg);
                    } else {
                        this.dataClone.selfCheckItems = res.data.data.selfCheckItems
                        this.dataClone.sceneCheckItems = res.data.data.sceneCheckItems
                    }
                    this.$Spin.hide()
                }).catch(e => {
                    this.$Message.error("自评台账详情数据获取失败")
                    this.$Spin.hide()
                })
            }

            this.$http.get(Api.queryCodeDetailBySortId + '/NOT-00006', {params: {}}).then((res) => {
                this.environmentProtectionList = res.data.data;
            });
        },
        computed: {
            currentUser() {
                return JSON.parse(sessionStorage('userId').get('userId'))
            },
            evaluationScore() {
                let evaluationScore = 0
                let involvedScore = 0
                for (let i = 0, il = dataClone.sceneCheckItems.length; i < il; i++) {
                    let obj = dataClone.sceneCheckItems[i]
                    if ((!obj.score || !obj.ifInvolved) && obj.project !== '加分项' && obj.project !== '扣分项') {
                        if (!obj.ifInvolved) {
                            obj.problem = ''
                        }
                        obj.deductScore = 0
                        evaluationScore += 0
                    } else {
                        if (obj.project === '加分项' || obj.project === '扣分项') {
                            if (!obj.ifInvolved) {
                                obj.deductScore = 0
                                // evaluationScore+= 0
                                // involvedScore += 0
                            } else {
                                // if (obj.project === '扣分项') {
                                evaluationScore += obj.deductScore
                                // }
                                // involvedScore += 0 - obj.deductScore
                            }
                        } else {
                            evaluationScore += obj.deductScore
                            involvedScore += obj.score
                        }
                    }
                }
                this.dataClone.involvedScore = involvedScore
                this.dataClone.evaluationScore = involvedScore - evaluationScore
                this.dataClone.integretedScore = involvedScore === 0 ? 0 : (this.dataClone.evaluationScore / involvedScore * 500).toFixed(2)
                return this.dataClone.evaluationScore
            }
        },
        methods: {
            ...pageCommonFunction,
            // 点击取消。发出关闭弹出框事件
            handleCancel() {
                this.$emit('close-dialog')
            },
            // 发出保存成功事件
            handleSaveSuccess() {
                this.$emit('save-success')
            },
            setOrgId(data) {
                this.$set(this.dataClone, 'companyId', data[data.length - 1]);
            },
            setOrgName(data) {
                this.$set(this.dataClone, 'companyName', data);
            },
            /*  setSelfLevelTime(date) {
                  this.dataClone.levelTime = date
                  this.dataClone.auditTime = date
              },
              clearSelfLevelTime() {
                  this.dataClone.auditTime = ''
                  this.dataClone.levelTime = ''
              },*/
            setAuditor(data) {
                this.$set(this.dataClone, 'auditor', data[data.length - 1]);
            },
            // 清空否决项
            cleanVetoContent(value) {
                if (value == 0) {
                    this.dataClone.vetoContent = ' ';
                }
            },
            // 一行自评相关操作
            addRowStandard(type) {
                /*this.dialogResourceType = type;
                console.log(this.currentUser)
                this.selectDialogShow = true*/
                this.formLoading = true
                let data = {
                    startPage: 0,
                    size: 0,
                    reportId: this.dataClone.id,
                    curCompanyId: this.dataClone.companyId,
                    industryName: this.dataClone.industryName.join(','),
                    belongOrgId: this.dataClone.belongOrgId,
                    year: this.dataClone.year
                };
                this.$http.get(this.dialogResourceQueryUrl, {params: data}).then((res) => {
                    if (res.data.status === 201) {
                        this.$Message.error(res.data.msg);
                    }
                    this.dataClone[type] = []
                    let involvedScore = 0
                    res.data.data.data.forEach(item => {
                        this.dataClone[type].push({
                            ...item,
                            // ifInvolved: true,
                            // id:this.get_uuid(),
                            // problem: item.score ?'':'无',
                            // deductScore: !item.score&&item.project !== '加分项' && item.project !== '扣分项' ?'':0,
                        })
                        if (item.score) {
                            involvedScore += item.score
                        } else {
                            involvedScore += 0
                        }
                    })
                    this.dataClone.evaluationScore = involvedScore
                    this.dataClone.involvedScore = involvedScore
                    this.dataClone.standardScore = involvedScore
                    if (res.data.data.data.length < 1) {
                        this.$Message.error("集团尚未维护生态环境标准化指标")
                    }
                    this.formLoading = false
                }).catch(e => {
                    this.formLoading = false
                    this.$Message.error("数据获取失败")
                })
            },
            /*
                        selectItemTableSubmitBtnClickHandle() {
                            this.selectDialogShow = false
                            var selectedArr = this.$refs.selectItemTable.getSelectedDataArr()
                            selectedArr.forEach(item => {
                                this.dataClone[this.dialogResourceType].push({
                                    ...item,
                                    // project standard
                                    problem: '',
                                    ratingScore: item.score,
                                    rectificationDetail: undefined,
                                    deductScore: '',
                                })
                            })

                        },
            */
            removeRowStandard(type, index) {
                this.dataClone.involvedScore = this.dataClone.involvedScore - 0 - this.dataClone[type][index].score
                this.dataClone[type].splice(index, 1)
                // this.$refs['selfCheckForm'].validateField(type)
            },
            reportQuestion(row,index,type){
                this.$Modal.confirm({
                    title: '提示',
                    content: '<p>是否要上报？</p>',
                    onOk: () => {
                        this.$http.post(Api.reportQuestionAccount, row).then((res) => {
                            if (res.data.status === 200) {
                                this.$Message.info('上报成功')
                                this.dataClone[type][index].state = 'NOT_RECTIFIED'
                            } else if (res.data.status === 201) {
                                this.$Message.error(res.data.msg);
                            }
                        }).catch(e => {
                            this.$Message.error("上报异常");
                        })
                    },
                    onCancel: () => {}
                })
            },
            saveOne(row, index, type) {
                this.$refs['itemForm'].validate((valid) => {
                    if (valid) {
                        this.$Modal.confirm({
                                title: '提示',
                                content: '<p>是否要提交？</p>',
                                onOk: () => {
                                    row.createUserId = this.currentUser.userId
                                    row.createOrgId = this.currentUser.orgId
                                    row.companyId = this.dataClone.companyId
                                    row.belongOrgId = this.dataClone.belongOrgId
                                    row.businessId = row.id
                                    row.priBusinessId = this.dataClone.id
                                    row.accountType = 2
                                    this.$http.post(Api.updateEnvSelfCheckItem, row).then((res) => {
                                        if (res.data.status === 200) {
                                            this.$Message.info('保存成功')
                                            row.createUserName = this.currentUser.userName
                                            this.dataClone[type][index].createUserName = this.currentUser.userName
                                            this.dataClone[type][index].problemCategory = row.problemCategory
                                            this.dataClone[type][index].problemCategoryName = row.problemCategoryName
                                            this.dataClone[type][index].deductScore = row.deductScore
                                            this.dataClone[type][index].ifInvolved = row.ifInvolved
                                            this.dataClone[type][index].problem = row.problem
                                            this.dataClone[type][index].problemDesc = row.problem
                                            this.dataClone[type][index].checkTime = row.checkTime
                                            this.dataClone[type][index].completeTime = row.completeTime
                                        } else if (res.data.status === 201) {
                                            this.$Message.error(res.data.msg);
                                        }
                                        this.itemModel=false
                                        this.questionItem={}
                                    }).catch(e => {
                                        this.$Message.error("保存异常");
                                    })
                                },
                            onCancel: () => {}
                        })
                    }else {
                        this.$Message.error('请填报完整!');
                    }
                })
            },
            // 提交
            submit(name) {
                if (this.sending) return
                if (this.dataClone.sceneCheckItems.length < 1) {
                    this.$Message.error("现场审核中发现的其他不符合项至少一条！")
                    return
                }
                this.$refs[name].validate((valid) => {
                    if (valid) {
                        let url = Api.updateEnvSelfCheck
                        if (this.mode === 'add') {
                            url = Api.saveEnvSelfCheck
                        }
                        this.dataClone.levelType = '2'
                        this.sending = true
                        this.$emit('sending', true)
                        this.$http.post(url, this.dataClone).then((res) => {
                            if (res.data.status === 200) {
                                this.$Message.success(this.mode === 'add' ? '添加成功' : '编辑成功');
                                this.handleSaveSuccess()
                            } else if (res.data.status === 201) {
                                this.$Message.error(res.data.msg);
                            }
                            this.sending = false
                            this.$emit('sending', false)
                        }).catch(e => {
                            this.$Message.error("提交失败")
                            this.sending = false
                            this.$emit('sending', false)
                        })
                    } else {
                        this.$Message.error('请填报完整!');
                    }
                })
            },

            viewPicture(id) {
                this.id = id
                this.uploadList = [];
                let url = this.viewUrl + '/' + id + '/files/picture'
                this.$http.get(url + "?field=selfChecke").then((res) => {
                    if (res.data.result == "success") {
                        console.log(res.data)
                        res.data.data.map((item) => {
                            this.uploadList.push({
                                name: item.fileName,
                                id: item.id,
                                url: Api.downloadPTWSchemeFile + '/' + item.id
                            });
                        });
                    }
                })
            },
            handleView(name, url) {
                this.viewUrl = url;
                this.imgName = name;
                this.visible = true;
            },
            handleRemove(item) {
                console.log(item)
                let url = this.viewUrl + '/file/' + item.id;
                this.$http.delete(url).then((res) => {
                    this.viewPicture(this.id)
                })
            },
            handleBeforeUpload(file) {
                if (file.size > 1024 * 1024) {
                    this.$Message.error('图片不能大于1M.');
                    return false;
                }
                let index = file.name.lastIndexOf(".");
                let suffix = file.name.substr(index + 1).toLowerCase();
                if (suffix != 'jpg' && suffix != 'jpeg' && suffix != 'png' && suffix != 'gif') {
                    this.$Message.error("请上传jpg,jpeg,png,gif格式的图片");
                    return false;
                }
                let check = this.uploadList.length < 9;
                if (!check) {
                    this.$Message.error('最多上传9张图片');
                    return false;
                }
                let formData = new FormData();
                formData.append("files", file);
                this.$http.post(this.viewUrl + '/' + this.id + '/files/picture/selfChecke', formData).then((res) => {
                    if (res.data.result == "success") {
                        this.$Message.success("上传成功");
                        this.viewPicture(this.id)
                    } else {
                        this.$Message.error("附件上传失败");
                    }
                }).catch(e => {
                    console.log(e);
                    this.$Message.error("数据获取失败");
                })
                return false;
            },
            rowClassName(row, index) {
                if (row.ifInvolved) {
                    return '';
                } else {
                    return 'demo-table-ifInvolved-row';
                }
            }
        },
        components: {
            cascaderDom,
            SelectItemTable
        },
    }
</script>

<style scoped>
    /deep/ .ivu-table .demo-table-ifInvolved-row td {
        background-color: #ffb61e;
        color: #fff;
    }

    .mb10 {
        margin-bottom: 10px;
    }

    .aR {
        text-align: right;
    }

    .fixed:after {
        display: block;
        content: '';
        clear: both;
        width: 100%;
        height: 0;
    }

    .self-check-form {
    }

    /deep/ .self-check-form .ivu-form-item {
        /*margin-bottom: 24px;*/
    }

    /deep/ .self-check-form .ivu-table-wrapper {
        overflow: visible;
    }

    /deep/ .self-check-form .ivu-table-wrapper .ivu-table {
        overflow: visible;
    }

    .demo-upload-list {
        display: inline-block;
        width: 60px;
        height: 60px;
        text-align: center;
        line-height: 60px;
        border: 1px solid transparent;
        border-radius: 4px;
        overflow: hidden;
        background: #fff;
        position: relative;
        box-shadow: 0 1px 1px rgba(0, 0, 0, .2);
        margin-right: 4px;
    }

    .demo-upload-list img {
        width: 100%;
        height: 100%;
    }

    .demo-upload-list-cover {
        display: none;
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        background: rgba(0, 0, 0, .6);
    }

    .demo-upload-list:hover .demo-upload-list-cover {
        display: block;
    }

    .demo-upload-list-cover i {
        color: #fff;
        font-size: 20px;
        cursor: pointer;
        margin: 0 2px;
    }
</style>
